from django_redis import get_redis_connection

from utils import hmjson


# todo 购物车合并
def merge_cart_cookie2redis(request, response, user_id):
    """
    读取cookie中的购物车数据，保存到redis中
    :param request: 用于读取cookie中的购物车数据
    :param response: 合并完成后，删cookie中的购物车数据
    :return: response
    """

    # 读取cookie
    cart = request.COOKIES.get('cart')
    if not cart:
        return response

    # 转成字典
    cart_dic = hmjson.loads(cart)
    print(cart_dic,'0000000000000000000000')
    # 写redis
    redis_cli = get_redis_connection('cart')

    # 遍历COOKIE中的字典，值是一个字典
    for sku_id, item in cart_dic.items():
        # 将数据保存到hash中
        # request.user===>获取当前登陆用户
        # 当函数会在登陆时执行，此时登陆还没有完成，所以request对象中并没有user属性
        redis_cli.hset('cart%d' % user_id, sku_id, item.get('count'))
        if item.get('selected'):
            redis_cli.sadd('cart_selected%d' % user_id, sku_id)
        else:
            redis_cli.srem('cart_selected%d' % user_id, sku_id)

    # 删除cookie
    response.delete_cookie('cart')
    return response
